import 'package:app_info/info/appsflyer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pinput/pinput.dart';
import 'package:smartloan_mdc/extension/extension.dart';
import 'package:smartloan_mdc/http/api/api.dart';
import 'package:smartloan_mdc/pages/auth/base_auth.dart';
import 'package:smartloan_mdc/pages/widgets/app_btn.dart';
import 'package:smartloan_mdc/pages/widgets/sms_code.dart';
import 'package:smartloan_mdc/pages/widgets/text_input.dart';
import 'package:smartloan_mdc/res/string.dart';
import 'package:smartloan_mdc/res/theme.dart';
import 'package:smartloan_mdc/utils/auth/auth.dart';
import 'package:smartloan_mdc/utils/loading/loading.dart';

import '../../route/app_routes.dart';
import '../../utils/locator/app_config.dart';
import '../../utils/locator/locator.dart';

class CodePage extends BaseAuth {
  const CodePage({super.key});

  @override
  BaseAuthState<BaseAuth> getBaseAuthState() => _CodePageState();
}

class _CodePageState extends BaseAuthState<CodePage> {

  @override
  String get pageName => 'codePage';

  SmsController smsCtrl = SmsController();

  bool showVoice1 = true;
  bool showVoice2 = false;
  bool showVoice3 = false;
  bool existed = false;
  bool isCounting = false;
  bool sendVoiceCode = false;

  String phone = "";
  String code = "";

  int count = 59;
  int initCount = 59;

  @override
  void initState() {
    phone = Get.arguments['phone'];
    existed = Get.arguments['existed'] ?? false;
    AppsFlyer().logEvent("code-visit");

    initSmsCtrl();
    super.initState();
  }

  @override
  Widget buildContent() {
    return Column(
      children: [
        20.h.hSizedBox(),
        pinput(),
        10.h.hSizedBox(),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            smsCode()
          ],
        ),
        20.h.hSizedBox(),
        AppBtn(
          content: AppStr.apply,
          onTap: apply,
        ),
        20.h.hSizedBox(),
        voiceTextShow(),
      ],
    ).marginSymmetric(horizontal: 15.w);
  }

  void initSmsCtrl() {
    SmsCodeListener listener = SmsCodeListener(
        onCount: (value){
          if (mounted) {
            setState(() {
              isCounting = true;
              count = value;

              if (sendVoiceCode) {
                // 语音验证码倒计时
                showVoice1 = false;
                showVoice2 = false;
                showVoice3 = true;
              } else {
                // 短信验证码倒计时
                showVoice1 = true;
                showVoice2 = false;
                showVoice3 = false;
              }

            });
          }
        },
        onComplete: (){
          if (mounted) {
            setState(() {
              isCounting = false;

              showVoice1 = false;
              showVoice2 = true;
              showVoice3 = false;
            });
          }
        }
    );
    smsCtrl.addListener(listener);
    smsCtrl.start(initCount: initCount);
  }

  Widget pinput() {
    return Pinput(
      length: 6,
      autofocus: true,
      defaultPinTheme: PinTheme(
        width: 55.r,
        height: 55.r,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          // border: Border(
          //   bottom: BorderSide(color: const Color(0xFF92D6C3), width: 2.w)
          // ),
          color: Colors.white
        ),
        textStyle: TextStyle(
          fontSize: 20.sp,
          fontWeight: FontWeight.bold,
          color: Colors.black
        )
      ),
      onChanged: (value) {
        // debugPrint('value: $value');
        code = value;
      },
      onCompleted: (value) {
        apply();
      },
      inputFormatters: [
        FilteringTextInputFormatter.digitsOnly
      ],
      // focusNode: pinFocusNode,
    );
  }

  Widget voiceTextShow() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Offstage(
          offstage: !showVoice1,
          child: Text("${AppStr.voiceText1}${count}s",
              style: TextStyle(color: Colors.white)),
        ),
        Offstage(
          offstage: !showVoice2,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              AppStr.voiceText2.sText(color: Colors.white),
              AppStr.smsText.sText(
                color: Colors.white,
                decoration: TextDecoration.underline
              ).onPress(() {
                sendCode(true);
              }),
            ],
          ),
        ),
        Offstage(
          offstage: !showVoice3,
          child: AppStr.voiceText3.sText(color: Colors.white),
        ),
      ],
    );
  }

  Widget smsCode() {
    return SmsCode(
      controller: smsCtrl,
      completeText: AppStr.getAgain,
    ).onPress(() {
      sendCode(false);
    });
  }

  void apply() async {
    if (codeCheck()) {
      try {
        showLoading();
        Map authRes = await RequestApi.userAuth(phone, code, isLogin: existed) as Map;
        Auth.login(authRes);
        Get.toNamed(AppRoutes.home, arguments: {
          'url': locator<AppConfig>().appConfigModel.baseUrl,
          'checkVersion': true
        });

      } on Exception catch (e) {
        // AppHttpBaseConfig().exceptionHandle(e);

      } finally {
        hideLoading();
      }

    }
  }

  bool codeCheck() {
    if (!getAgree) {
      AppStr.termCheck.toast(pageName: pageName);
      return false;
    }

    if (code.isEmpty) {
      AppStr.codeEmpty.toast(pageName: pageName);
      return false;
    }

    // 输入长度检测
    if (code.length < 6) {
      AppStr.codeIncorrect.toast(pageName: pageName);
      return false;
    }

    return true;
  }

  sendCode(bool isVoiceCode) async {
    showLoading();
    try {
      await RequestApi.getSmsCode(phone, existed ? 1 : 2, notifyType: isVoiceCode ? 2 : 1);
      setState(() {
        sendVoiceCode = isVoiceCode ? true : false;
      });
      smsCtrl.start(initCount: initCount);

    } on Exception catch (e) {
      // AppHttpBaseConfig().exceptionHandle(e);
    } finally {
      hideLoading();
    }

  }

}
